package com.atguigu.zkb.utils;



import com.atguigu.zkb.execption.GuiguException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义序列化和反序列化工具类
 */
public class Jsons {
    static Logger logger = LoggerFactory.getLogger(Jsons.class);
    final static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 反序列化
     * @param jsonContent json字符串
     * @param tClass 目标对象类型
     * @return 目标对象
     * @param <T> 目标对象类型
     */
    public static <T> T jsonToObj(String jsonContent, Class<T> tClass) {
        T t = null;
        try {
            return objectMapper.readValue(jsonContent, tClass);
        } catch (JsonProcessingException e) {
            // "abc"(转Map失败)--->"{"name":"hzk","age":18}"(转Map成功)
            logger.error("字符串:{}反序列化成对象:{}失败，原因是：{}", jsonContent, tClass, e.getMessage());
            throw new GuiguException(400, "服务器内部处理数据异常");
        }
    }
    public static <T> T jsonToObj(String jsonContent, TypeReference<T> tTypeReference) {
        T t = null;
        try {
            return objectMapper.readValue(jsonContent, tTypeReference);
        } catch (JsonProcessingException e) {
            // "abc"(转Map失败)--->"{"name":"hzk","age":18}"(转Map成功)
            logger.error("字符串:{}反序列化成对象:{}失败，原因是：{}", jsonContent, tTypeReference, e.getMessage());
            throw new GuiguException(400, "服务器内部处理数据异常");
        }
    }

    /**
     * 序列化
     * @param object 目标对象
     * @return json字符串
     */
    public static String objToStr(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            logger.error("对象:{}序列化成字符串失败，原因是：{}", object, e.getMessage());
            throw new GuiguException(400, "服务器内部处理数据异常");
        }
    }
    public static List<String> getAppAllRegex() {
        // 1.初始化所有的正则规则
        ArrayList<String> list = new ArrayList<>();
        list.add("^\\{\\}$");
        list.add("^null$");
        list.add("^\\[\\]$");
        return list;
    }
}
